import os
import time
import pandas as pd
from time import localtime, strftime


class CaseResult():
    def __init__(self, case_csv):
        self.click_steps = 0
        self.final_result = ''
        self.passed = 0
        self.wrong = 0
        self.failed = 0
        self.case_csv = case_csv
        self.all_result = []

    def get_result(self):
        df = pd.read_csv(self.case_csv, index_col=0)
        self.click_steps = df.shape[0]
        self.all_result = df.loc[:, '结果'].tolist()
        self.stat_result(self.all_result)
        status = self.write_result()
        return status

    def stat_result(self, result_data):
        if '失败' in result_data:
            self.final_result = '失败'
        elif '错误' in result_data:
            self.final_result = '错误'
        else:
            self.final_result = '通过'

        for i in result_data:
            if i == '通过':
                self.passed += 1
            elif i == '失败':
                self.failed += 1
            elif i == '错误':
                self.wrong += 1

    def write_result(self):
        stat_result = {
            '测试时间': strftime('%Y.%m.%d-%H:%M:%S ', localtime(time.time())),
            '测试结果': self.final_result,
            '测试步数': self.click_steps,
            '通过步数': self.passed,
            '失败步数': self.failed,
            '错误步数': self.wrong
        }

        data = pd.DataFrame([stat_result])
        result_path = self.case_csv.rsplit('/', 1)[0]+'/'
        # stat_result_file_name =  self.case_csv.rsplit('/', 1)[1].split('.')[0]
        data = data.loc[:, ~data.columns.str.contains('^Unnamed')]
        result_file = result_path + 'final_result.csv'
        data.to_csv(result_file, encoding="utf_8_sig")
        return True if os.path.exists(result_file) else False
